package com.spagettikod.t437;

import java.awt.Container;
import java.awt.Cursor;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;

import com.xerox.amazonws.sdb.Domain;

public class SimpleDBTable
{
	private static final long serialVersionUID = 2741534052269090471L;

	private JScrollPane tablePane;

	private JTable table;

	private JFrame topLevelContainer;

	public SimpleDBTable(Domain domain, Container topLContainer)
	{
		table = new JTable(new SimpleDBTableModel(domain));

		this.topLevelContainer = (JFrame) topLContainer;
		this.topLevelContainer.addComponentListener(new ComponentAdapter()
		{

			@Override
			public void componentResized(ComponentEvent arg0)
			{
				super.componentResized(arg0);
				topLevelContainer.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
				getModel().fetchData(getVisibleRows(), false);
				topLevelContainer.setCursor(Cursor.getDefaultCursor());
			}

		});

		createTableScrollPane();

		getModel().fetchData(getVisibleRows(), true);
	}

	private int getVisibleRows()
	{
		Float rows = new Float(topLevelContainer.getSize().height) / new Float(table.getRowHeight());
		return Math.round(rows.floatValue());
	}

	private SimpleDBTableModel getModel()
	{
		return (SimpleDBTableModel) table.getModel();
	}

	private void createTableScrollPane()
	{
		tablePane = new JScrollPane(table);

		tablePane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener()
		{

			public void adjustmentValueChanged(AdjustmentEvent e)
			{
				if (!e.getValueIsAdjusting())
				{
					if (getHorizontalScrollBarPercent() > 80)
					{
						topLevelContainer.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
						getModel().fetchData(getVisibleRows(), false);
						topLevelContainer.setCursor(Cursor.getDefaultCursor());
					}
				}
			}

		});
	}

	private int getHorizontalScrollBarPercent()
	{
		JViewport vp = tablePane.getViewport();

		Float correctedMaximumHeight = new Float(vp.getViewSize().height) - new Float(vp.getViewRect().height);
		Float currentPosition = new Float(vp.getViewRect().y) / correctedMaximumHeight;
		currentPosition = currentPosition * 100;

		return Math.round(currentPosition);
	}

	public JScrollPane getScrollPane()
	{
		return tablePane;
	}
}
